import { Context } from 'koa'
import { errorRes } from './responseModel'

export enum State {
    delete = 0, // 已删除
    expired = 1, // 过期
    unexpired = 2, // 未过期
    unavailable = 3, // 无效
    available = 4, // 有效
    disabled = 5, // 已禁用
    unknown = 6, // 未知
}

export const getType = (obj: unknown) => {
    if (obj === null) {
        return 'null'
    } else if (Array.isArray(obj)) {
        return 'array'
    } else {
        return Object.prototype.toString.call(obj).slice(8, -1).toLowerCase()
    }
}

export const bodyNotNull = (ctx: Context, arr: string[]) => {
    if (getType(ctx.request.body) === 'object') {
        const body = ctx.request.body as Record<string, any>
        arr.forEach(key => {
            if (!(key in body) || body[key] === null || body[key] === undefined || (Object.prototype.toString.call(body[key]).slice(8, -1) === 'String' && body[key].trim() === '')) {
                throw new errorRes(key + ' is required')
            }
        })
    }
}